package cn.edu.scau.cmil.linwei.comprehensive.Controller;

import cn.edu.scau.cmil.linwei.comprehensive.Script.DataField;
import cn.edu.scau.cmil.linwei.comprehensive.Script.Student;
import cn.edu.scau.cmil.linwei.comprehensive.Script.Teacher;
import cn.edu.scau.cmil.linwei.comprehensive.Script.User;
import cn.edu.scau.cmil.linwei.comprehensive.util.DataIO;
import cn.edu.scau.cmil.linwei.comprehensive.util.StageManager;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import static javafx.stage.StageStyle.UNDECORATED;

public class LoginController implements Initializable {

    public BorderPane borderPane;
    public Button LoginButton;
    public Button FotgetPWButton;
    public Button RegisterButton;
    public TextField IDInput;
    public PasswordField PWInput;
    public Text TipText;

    private String inputid = new String();
    private String inputpw = new String();

    public void CloseLoginWindows(){
        Stage primaryStage = (Stage)borderPane.getScene().getWindow();//通过布局获取场景再获取舞台
        StageManager.STAGEMAP.put("Login",primaryStage);//保存舞台
        StageManager.CONTROLLERMAP.put("LoginController",this);//保存控制器
        primaryStage.close();//关闭舞台
    }//关闭本页面

    //登录
    public int CheckIDANDPW(){
        System.out.println("登录，检查密码");
        inputid = IDInput.getText();
        inputpw = PWInput.getText();
        System.out.println("输入的帐号密码为"+inputid+" "+inputpw);
        User user;
        for(int i = 0 ;i<DataField.userData.size();i++){
            user = DataField.userData.get(i);
            System.out.println(user.ID+" "+user.PW+" "+user.Name+" "+user.UserKind+" "+user.InitQuestion+" "+user.InitAnswer);

            if(user.ID.equals(inputid)){
                if(user.PW.equals(inputpw)){//密码正确
                    DataField.LoginedUser = user;//将登录用户设为目标用户
                    return 1;//登录成功
                }
                else{//密码错误
                    return 2;
                }
            }
        }
        return 3;//查无此人
    }//检查帐号密码，登陆成功返回1，密码错误返回2，查无此人返回3

    public void AddLoginedStudentOrTeacher(){
        //从数据域teacherData或studentData中找到这位用户，找到后将引用放到数据域中，如果是管理员，不用添加信息
        String userkind = DataField.LoginedUser.UserKind;
        if(userkind.equals("1")){//如果是学生
            Student student;
            String userId = DataField.LoginedUser.ID;
            for(int i =0 ;i<DataField.studentData.size();i++) {
                student = DataField.studentData.get(i);
                if(student.ID.equals(userId)){//如果第i个学生就是当前用户
                    DataField.LoginedStudent = student;
                    break;
                }
            }//for
        }
        else if(userkind.equals("2")){//如果是老师
            Teacher teacher;
            String userId = DataField.LoginedUser.ID;
            for(int i =0 ;i<DataField.teacherData.size();i++) {
                teacher = DataField.teacherData.get(i);
                if(teacher.ID.equals(userId)){//如果第i个老师就是当前用户
                    DataField.LoginedTeacher = teacher;
                    break;
                }
            }//for
        }
    }//把登录的学生/教师对象赋值给数据域

    public void openTeacherMainWindows() throws Exception{
        Stage stage = new Stage();
        BorderPane root = FXMLLoader.load(getClass().getResource("/cn/edu/scau/cmil/linwei/comprehensive/FXML/TeacherMainWindows.fxml"));
        Scene scene = new Scene(root);

        stage.setScene(scene);
        System.out.println("您登录的用户信息为");
        System.out.println(DataField.LoginedUser.ID);
        System.out.println(DataField.LoginedUser.PW);
        System.out.println(DataField.LoginedUser.Name);
        System.out.println(DataField.LoginedUser.UserKind);
        System.out.println(DataField.LoginedUser.InitQuestion);
        System.out.println(DataField.LoginedUser.InitAnswer);
        stage.initStyle(StageStyle.TRANSPARENT);//隐藏默认的标题栏
        scene.setFill(null);
        stage.show();

    }//打开主界面

    public void Login(){//登录
        int CheckResult = CheckIDANDPW();//数据域中登录用户已在Check成功后设为user
        if(CheckResult == 1){
            //System.out.println("登录成功");
            TipText.setText(" ");
            CloseLoginWindows();//关闭窗口
            AddLoginedStudentOrTeacher();//识别用户类型，将登录的学生/老师的信息传到数据域
            try{
                openTeacherMainWindows();
            }
            catch (Exception e){ System.out.println("打开主窗口失败"+e);}
        }
        else if(CheckResult == 2){
            TipText.setText("您输入的密码有误");
        }
        else{
            TipText.setText("您输入的账户不存在");
        }
    }//登录，调用CheckIDANDPW()、AddLoginedStudentOrTeacher()、CloseLoginWindows()、openTeacherMainWindows()

    //忘记密码
    public void openForgetPWWindows() throws IOException {
        Stage stage = new Stage();
        BorderPane root = FXMLLoader.load(getClass().getResource("/cn/edu/scau/cmil/linwei/comprehensive/FXML/ForgetPW.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.showAndWait();
    }//打开忘记密码页面

    public void ForgetPW() throws IOException {
        CloseLoginWindows();
        openForgetPWWindows();
    }//忘记密码


    //注册
    public void openRegisterWindows() throws Exception{
        Stage stage = new Stage();
        BorderPane root = FXMLLoader.load(getClass().getResource("/cn/edu/scau/cmil/linwei/comprehensive/FXML/Register.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.showAndWait();
    }//打开注册页面

    public void Register(){
        CloseLoginWindows();
        try{
            openRegisterWindows();
        }
        catch (Exception e){
            System.out.println(e);
        }
    }//注册调用openRegisterWindows()

    //标题栏最小化、关闭、拖拽
    private double oldStageX,oldStageY,oldScreenX,oldScreenY;//点击时记录窗口的XY
    //最小化
    public void MinButtonClicked(){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.setIconified(true);
    }//设置最小化按钮点击时发生的活动选项
    //关闭
    public void CloseButtonClicked(){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.close();
    }//设置关闭按钮点击时发生的活动选项
    //鼠标拖拽
    public void MousePressed(MouseEvent event){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        oldStageX = stage.getX();//事件相对于MouseEvent源的原点的水平位置，即获取当前鼠标位置
        oldStageY = stage.getY();//事件相对于MouseEvent源的原点的垂直位置，即获取当前鼠标位置
        oldScreenX = event.getScreenX();//返回事件的绝对水平位置，即获取窗口左上角位置
        oldScreenY = event.getScreenY();//返回事件的绝对垂直位置，即获取窗口左上角位置
    }

    public void MouseDragged(MouseEvent event){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.setX(event.getScreenX()-oldScreenX+oldStageX);
        stage.setY(event.getScreenY()-oldScreenY+oldStageY);
    }


    //从文件中读取信息
    public void loadInfo() throws IOException {
        DataIO.UserRead();//读取用户帐号密码等数据
        //DataIO.UserWrite();

        DataIO.ScoreRead();//将数据读入ArrayList
        //DataIO.ScoreWrite();//将数据从ArrayList写入文本

        DataIO.TeacherRead();
        //DataIO.TeacherWrite();

        DataIO.StudentRead();
        DataIO.StudentWrite();

        DataIO.WhiteListRead();
        //DataIO.WhiteListWrite();

        DataIO.GradeRead();
        //DataIO.GradeWrite();

        DataIO.MajorRead();
        //DataIO.MajorWrite();

        DataIO.CourseRead();
        //DataIO.CourseWrite();

        DataIO.ClassRead();
        //DataIO.ClassWrite();
    }


    @Override
    public void initialize(URL location, ResourceBundle resources){
        IDInput.requestFocus();//输入帐号的框获取焦点
        try{
            loadInfo();
        }
        catch (Exception e){
            System.out.println("读取信息失败"+e);
        }
    }

}
